//
//  AppDelegate.m
//  AssetsInventory
//
//  Created by 李沛池 on 2017/11/16.
//  Copyright © 2017年 李沛池. All rights reserved.
//

#import "AppDelegate.h"
#import "AITools.h"
#import "LPCSVProgressHUD.h"
#include <objc/runtime.h>

@interface AppDelegate ()

@end

@implementation AppDelegate
{
    NSTimer *_timer;
    int _countDown;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    NSLog(@"NSHomeDirectory = %@",NSHomeDirectory());
    
    //调用网络请求 以确保用户在此层级已经选择完首次进入app产生的系统网络请求弹窗
    [AITools networkStatus];
    
    [self openBackTimer];
    
    return YES;
}

//保持后台可运行定时器
- (void)openBackTimer
{
    UIApplication*   app = [UIApplication sharedApplication];
    __block    UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    _countDown = 0;
    _timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode: UITrackingRunLoopMode];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    
    [_timer invalidate];
    _countDown = 0;
    NSLog(@"%@",@(_countDown));
}

- (void)timerAction
{
    _countDown += 5;
    NSLog(@"%@",@(_countDown));
    if (_countDown >= 60 * 5) { // 五分钟后关闭应用
        exit(0);
    }
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    NSString *urlString = [url absoluteString];
    
    NSString *strHXId = @"LHSMAppIOSAssetsInventory";
//    strHXId = @"petrochina.jdyt.zcpd";
    
    NSString *strHXURL = [NSString stringWithFormat:@"%@://?action=login&params=",strHXId];
    if ([urlString hasPrefix:strHXURL]) {
        NSRange rangePrefix = [urlString rangeOfString:strHXURL];
        
        NSString *urlencodeJSONDic = [urlString substringWithRange:NSMakeRange([urlString rangeOfString:strHXURL].length, urlString.length - rangePrefix.length)];
        //反解urlencode
        NSString *strJSONDic = [urlencodeJSONDic stringByRemovingPercentEncoding];
        NSData *jsonData = [strJSONDic dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dicJSON = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
//        LPCHUDShowMessage(strJSONDic);
        //保存到瑞信自动登录信息
        [[NSUserDefaults standardUserDefaults] setObject:[AITools objectToJSONString:dicJSON] forKey:@"AIRUIXINAutoLoginInfo"];
        [[NSUserDefaults standardUserDefaults] setObject:[AITools objectToJSONString:dicJSON] forKey:@"AILoginInfo"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    return YES;
}


@end
